package edu.friday.common.security.filter;

import edu.friday.common.security.LoginUser;
import edu.friday.common.security.service.TokenService;
import edu.friday.utils.StringUtils;
import edu.friday.utils.security.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Component
//继承OncePerRequestFilter：保证每次请求只会拦截（过滤）一次
public class JwtAuthenticationTokenFilter extends OncePerRequestFilter {

    @Autowired
    TokenService tokenService;
    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
            throws ServletException, IOException {
//  1.获取LoginUser对象
        LoginUser loginUser = tokenService.getLoginUser(request);
        //2.LoginUser对象不为空 Authentication 存储到 SecurityContext  上下文
        //StringUtils.isNull 第一次请求为空，把值设置进去，后面请求中不做判断
        if(StringUtils.isNotNull(loginUser)&&StringUtils.isNull(SecurityUtils.getAuthentication())){
            UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(loginUser,null, loginUser.getAuthorities());
            authenticationToken.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
            SecurityContextHolder.getContext().setAuthentication(authenticationToken);
        }
        //3。LoginUser验证token
        filterChain.doFilter(request,response);
    }
}
